package com.ciwong.epaper.modules.me.ui;

import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.epaper.adapter.BookDeskAdapter;
import com.ciwong.epaper.modules.epaper.bean.EpaperInfo;
import com.ciwong.epaper.modules.epaper.bean.GradeBean;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.me.adapter.BookCategoryDeskGridAdapter;
import com.ciwong.epaper.modules.me.adapter.BookDeskGridAdapter;
import com.ciwong.epaper.modules.me.bean.BookMarkPageInfo;
import com.ciwong.epaper.modules.me.bean.EpaperInfoGradeCategoryBean;
import com.ciwong.epaper.modules.me.bean.EpaperInfoGradeNameBean;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.me.widget.MarginDecoration;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DisplayUtils;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.utils.GsonUtil;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.BaseQuickOnItemClickListener;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.widget.NoScrollGridView;

import java.util.ArrayList;
import java.util.List;

/**
 * 标签书籍页面
 * 书籍UI和书桌旧版用的是同一个UI布局和ADAPTER  修改的时候需要注意一下
 */

public class BookTagActivity extends BaseActivity implements OnRefreshListener, OnLoadMoreListener {
    private RecyclerView mRvBookDesk;
    private BookDeskAdapter mBookDeskAdapter;
    private List<EpaperInfo> mEpaperInfoList = new ArrayList<>();
    private SwipeToLoadLayout mSwipeToLoadLayout;
    private int mBookmarkId;
    private int mPageIndex = 1;
    private int mPageSize = 15;
    private String mBookmarkTitle;
    private boolean mIsRefesh;
    private LinearLayout list_nodata;
    private ViewGroup listviewgroup;
    private Button btn_retry;
    private NoScrollGridView grand_name_grid;
    private BookDeskGridAdapter bookDeskGridAdapter;
    private List<EpaperInfoGradeNameBean> epaperInfoGradeNameBeans = new ArrayList<>();
    private int gradeId;

    //new
    private boolean isShowSubCategory = false;
    private NoScrollGridView grand_category_grid;
    private List<EpaperInfoGradeCategoryBean> mInfoGradeCategoryBean = new ArrayList<>();
    private BookCategoryDeskGridAdapter bookCategoryDridAdapter;
    private int mBookTypeId = 0;
    //服务器请求
    private int subCategoryId = 0;


    @Override
    protected int setView() {
        return R.layout.fragment_book_desk;
    }

    @Override
    protected void findViews() {
        mRvBookDesk = findViewById(R.id.swipe_target);
        mSwipeToLoadLayout = findViewById(R.id.swipe_toLoad_layout);
        list_nodata = findViewById(R.id.ll_no_net);
        listviewgroup = findViewById(R.id.listviewgroup);
        btn_retry = findViewById(R.id.btn_retry);
        grand_name_grid = findViewById(R.id.grand_name_grid);
        grand_category_grid = findViewById(R.id.grand_category_grid);
        findViewById(R.id.rl_top_chose).setVisibility(View.VISIBLE);

    }

    @Override
    protected void initEvent() {
        setImgRightBtn(R.mipmap.icon_search);
        setImgRightBtnListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {
                EpaperJumpManager.jumpToSerachBook(R.string.go_back, BookTagActivity.this, RequestCode.BookDeskResquestCode.REQ_CODE_TO_SEARCH_BOOK);
            }
        });
        mSwipeToLoadLayout.setOnRefreshListener(this);
        mSwipeToLoadLayout.setOnLoadMoreListener(this);
        btn_retry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadData();
            }
        });
    }

    @Override
    protected void init() {
        mRvBookDesk.setLayoutManager(new GridLayoutManager(BookTagActivity.this, 3));
        mRvBookDesk.addItemDecoration(new MarginDecoration(BookTagActivity.this));
        mBookDeskAdapter = new BookDeskAdapter(R.layout.item_autonomic_book_case, mEpaperInfoList);
        mRvBookDesk.setAdapter(mBookDeskAdapter);
        bookDeskGridAdapter = new BookDeskGridAdapter(BookTagActivity.this, epaperInfoGradeNameBeans);
        grand_name_grid.setAdapter(bookDeskGridAdapter);
        CWLog.e("DisplayUtils ", DisplayUtils.getWidthInDp(BookTagActivity.this) + "");
        if (DisplayUtils.getWidthInDp(BookTagActivity.this) >= 900) {
            grand_name_grid.setNumColumns(6);
            grand_category_grid.setNumColumns(6);
        } else if (DisplayUtils.getWidthInDp(BookTagActivity.this) >= 700 && DisplayUtils.getWidthInDp(BookTagActivity.this) < 900) {
            grand_name_grid.setNumColumns(5);
            grand_category_grid.setNumColumns(5);
        }else if (DisplayUtils.getWidthInDp(BookTagActivity.this) >= 500 && DisplayUtils.getWidthInDp(BookTagActivity.this) < 700) {
            grand_name_grid.setNumColumns(4);
            grand_category_grid.setNumColumns(4);
        }else{
            grand_name_grid.setNumColumns(3);
            grand_category_grid.setNumColumns(4);
        }

        mBookDeskAdapter.setOnItemClickListener(new BaseQuickOnItemClickListener() {
            @Override
            public void avertRepeatOnClick(BaseQuickAdapter adapter, View view, int position) {
                try {
                    EpaperInfo epaperInfo = mEpaperInfoList.get(position);
                    if (null != epaperInfo) {
                        if (epaperInfo.getIsExpire() == 1 || epaperInfo.getIsFree() == 1) {
                            EpaperJumpManager.jumpToCatalog(R.string.go_back, BookTagActivity.this, epaperInfo, IntentValue.JumpToBookCatalogType.FROM_NEW_DESK_BOOK, -1, epaperInfo.getServerId());
                        } else {
                            MeJumpManager.jumpBuyService(BookTagActivity.this, R.string.go_back, epaperInfo.getServerId(), -1, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY, "");
                        }
                    }
                } catch (Exception e) {

                }
            }
        });
    }

    @Override
    protected void loadData() {
        mBookmarkId = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_BOOKMARK, -1);
        mBookmarkTitle = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_TITLE);
        setTitleText(mBookmarkTitle);
        setGrade();
        mIsRefesh = true;
        mPageIndex = 1;
        if (!NetworkUtils.isOnline()) {
            list_nodata.setVisibility(View.VISIBLE);
            listviewgroup.setVisibility(View.GONE);
        } else {
            list_nodata.setVisibility(View.GONE);
            listviewgroup.setVisibility(View.VISIBLE);
            getGradeByBookmarkId();
            getBookBooksFromNet(mPageIndex);
            if (mBookmarkTitle.equals("听说")) {
                isShowSubCategory = true;
                mBookTypeId = 3;
            } else if (mBookmarkTitle.equals("跟读")) {
                mBookTypeId = 9;
                isShowSubCategory = true;
            } else {
                mBookTypeId = 0;
                isShowSubCategory = false;
            }
            if (isShowSubCategory) {
                findViewById(R.id.rl_top_sub_category_layout).setVisibility(View.VISIBLE);
                initCategoryDate();
            } else {
                findViewById(R.id.rl_top_sub_category_layout).setVisibility(View.GONE);
            }
        }
    }

    private void initCategoryDate() {
        bookCategoryDridAdapter = new BookCategoryDeskGridAdapter(BookTagActivity.this, mInfoGradeCategoryBean);
        grand_category_grid.setAdapter(bookCategoryDridAdapter);
        getGradeByBookCategoryId();
    }

    /**
     * 填充网络数据
     *
     * @param gradeList
     */
    public void setNetCategoryGrade(List<EpaperInfoGradeCategoryBean> gradeList) {
        mInfoGradeCategoryBean = new ArrayList<>();
        EpaperInfoGradeCategoryBean epaperInfoGradeNameBean = new EpaperInfoGradeCategoryBean();
        epaperInfoGradeNameBean.setName("全部");
        epaperInfoGradeNameBean.setID(0);
        epaperInfoGradeNameBean.setChecked(true);
        mInfoGradeCategoryBean.add(epaperInfoGradeNameBean);
        for (int i = 0; i < gradeList.size(); i++) {
            EpaperInfoGradeCategoryBean item = gradeList.get(i);
            EpaperInfoGradeCategoryBean itemGrade = new EpaperInfoGradeCategoryBean();
            itemGrade.setName(item.getName());
            itemGrade.setID(item.getID());
            itemGrade.setChecked(false);
            mInfoGradeCategoryBean.add(itemGrade);
        }
        bookCategoryDridAdapter.setNewData(mInfoGradeCategoryBean);
    }


    public void getGradeByBookCategoryId() {
        EpaperDao.getInstance().getGradeByBookCategoryId(mBookTypeId, new BaseExtCallBack(BookTagActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void success(final Object data) {
                if (null != data) {
                    List<EpaperInfoGradeCategoryBean> gradeList = (List<EpaperInfoGradeCategoryBean>) data;
                    Log.e("success data ", GsonUtil.toJson(gradeList));
                    setNetCategoryGrade(gradeList);
                }
            }

            @Override
            public void failed(int errorCode, Object data) {
                //网络获取失败了再走本地获取流程
                super.failed(errorCode, data);
            }

            @Override
            public void failed(Object data) {
                super.failed(data);
            }
        });
    }

    /**
     * 获取书籍
     *
     * @param pageIndex 页码
     */
    public void getBookBooksFromNet(int pageIndex) {
        EpaperDao.getInstance().getProductsbybookmark(EApplication.BRAND_ID, mBookmarkId, gradeId, subCategoryId, pageIndex, mPageSize, new BaseExtCallBack(BookTagActivity.this) {
            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                mSwipeToLoadLayout.setRefreshing(false);
                mSwipeToLoadLayout.setLoadingMore(false);
                hideCricleProgress();
            }

            @Override
            public void failed(Object data) {
                super.failed(data);
                mSwipeToLoadLayout.setRefreshing(false);
                mSwipeToLoadLayout.setLoadingMore(false);
                hideCricleProgress();
            }

            @Override
            public void success(Object data) {
                mSwipeToLoadLayout.setRefreshing(false);
                mSwipeToLoadLayout.setLoadingMore(false);
                hideCricleProgress();
                try {
                    if (data != null && data instanceof BookMarkPageInfo) {
                        BookMarkPageInfo bookMarkPageInfo = (BookMarkPageInfo) data;

                        List<EpaperInfo> epaperInfoList = bookMarkPageInfo.getProduct();
                        if (mIsRefesh) {
                            if (epaperInfoList != null && epaperInfoList.size() >= 0) {
                                mEpaperInfoList = epaperInfoList;
                                mBookDeskAdapter.setNewData(mEpaperInfoList);
                            }
                        } else {
                            if (epaperInfoList != null && epaperInfoList.size() >= 0) {
                                mEpaperInfoList.addAll(epaperInfoList);
                                mBookDeskAdapter.addData(epaperInfoList);
                            }
                        }

                    }
                } catch (Exception e) {
                    e.getStackTrace();
                }
            }
        });
    }

    /**
     * 获取书籍
     *
     * @param gradeId       年级id
     * @param isNeedRefresh 是否选择年级刷新数据
     */
    public void getServiceProductsByIdClassids(int gradeId, final boolean isNeedRefresh) {
        this.gradeId = gradeId;
        if (isNeedRefresh) {
            onRefresh();
        }
    }


    public void getServiceProductsByIdCategoryids(int categoryId, final boolean isNeedRefresh) {
        this.subCategoryId = categoryId;
        if (isNeedRefresh) {
            onRefresh();
        }
    }

    /**
     * 获取书籍包含的年级列表
     */
    public void getGradeByBookmarkId() {
        EpaperDao.getInstance().getGradeByBookmarkId(EApplication.BRAND_ID, mBookmarkId, new BaseExtCallBack(BookTagActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void success(final Object data) {
                if (null != data) {
                    List<GradeBean> gradeList = (List<GradeBean>) data;
                    setNetGrade(gradeList);
                }
            }

            @Override
            public void failed(int errorCode, Object data) {
                //网络获取失败了再走本地获取流程
                super.failed(errorCode, data);
            }

            @Override
            public void failed(Object data) {
                super.failed(data);
            }
        });
    }

    /**
     * 填充网络数据
     *
     * @param gradeList
     */
    public void setNetGrade(List<GradeBean> gradeList) {
        epaperInfoGradeNameBeans = new ArrayList<>();
        EpaperInfoGradeNameBean epaperInfoGradeNameBean = new EpaperInfoGradeNameBean("全部", 0, true);
        epaperInfoGradeNameBean.setGradeName("全部");
        epaperInfoGradeNameBean.setGradeId(0);
        epaperInfoGradeNameBean.setChecked(true);
        epaperInfoGradeNameBeans.add(epaperInfoGradeNameBean);
        for (int i = 0; i < gradeList.size(); i++) {
            GradeBean item = gradeList.get(i);
            EpaperInfoGradeNameBean itemGrade = new EpaperInfoGradeNameBean(item.getGradeName(), item.getGrade());
            epaperInfoGradeNameBeans.add(itemGrade);
        }
        bookDeskGridAdapter.setNewData(epaperInfoGradeNameBeans);
    }

    /**
     * 初始化本地数据
     */
    public void setGrade() {
        epaperInfoGradeNameBeans = new ArrayList<>();
        EpaperInfoGradeNameBean epaperInfoGradeNameBean = new EpaperInfoGradeNameBean("全部", 0, true);
        epaperInfoGradeNameBean.setGradeName("全部");
        epaperInfoGradeNameBean.setGradeId(0);
        epaperInfoGradeNameBean.setChecked(true);
        epaperInfoGradeNameBeans.add(epaperInfoGradeNameBean);
        EpaperInfoGradeNameBean epaperInfoGradeNameBean7 = new EpaperInfoGradeNameBean("七年级", 1107);
        EpaperInfoGradeNameBean epaperInfoGradeNameBean8 = new EpaperInfoGradeNameBean("八年级", 1108);
        EpaperInfoGradeNameBean epaperInfoGradeNameBean9 = new EpaperInfoGradeNameBean("九年级", 1109);
        EpaperInfoGradeNameBean epaperInfoGradeNameBean14 = new EpaperInfoGradeNameBean("其他", 333333);
        epaperInfoGradeNameBeans.add(epaperInfoGradeNameBean7);
        epaperInfoGradeNameBeans.add(epaperInfoGradeNameBean8);
        epaperInfoGradeNameBeans.add(epaperInfoGradeNameBean9);
        epaperInfoGradeNameBeans.add(epaperInfoGradeNameBean14);
        bookDeskGridAdapter.setNewData(epaperInfoGradeNameBeans);
    }

    @Override
    public void onRefresh() {
        mIsRefesh = true;
        mPageIndex = 1;
        getBookBooksFromNet(mPageIndex);
    }

    @Override
    public void onLoadMore() {
        mIsRefesh = false;
        mPageIndex++;
        getBookBooksFromNet(mPageIndex);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY:
                    onRefresh();
                    break;
            }
        }
    }
}

